#include <optional>
#include <nice2d/sprite.h>
#include <nice2d/actions/fadeoutaction.h>

class FadeoutActionData
{
public:
    std::optional<float> vel;
};

FadeoutAction::FadeoutAction(float duration):
    FiniteTimeAction(duration),
    data(new FadeoutActionData())
{
}

FadeoutAction::~FadeoutAction()
{
}

void FadeoutAction::update(float deltaTime)
{
    auto owner = getOwner();
    if (owner.expired())
        return;

    auto target = std::dynamic_pointer_cast<Sprite>(owner.lock());

    if (!data->vel.has_value())
        data->vel = 1.0f / getDuration();

    if (data->vel.has_value()) {
        auto color = target->getSpriteColor();
        int32_t alpha = color.a - 255 * data->vel.value() * deltaTime;
        if (alpha <= 0) {
            stop();
        } else {
            color.a = alpha;
            target->setSpriteColor(color);
        }
    }
}
